import { fetchJobs } from '../services/jobs.js'
import { readHtml, writeJson } from '../common/utils.js'
import HtmlQuery from '../common/html_query.js'
import _ from 'lodash'

const keys1 = [
    'name', 'user', 'time', 'type', 'status', 'money', 'location', 'businessTime',
    'beloneLocation', 'creditCode', 'checkTime', 'oldName', 'orang', 'industry', 'scope'
]

const parseHtml = (html: any) => {
    const query = new HtmlQuery(html)
    setupQueryRules(query)
    return query.build()
}

const setupQueryRules = (query: any) => {

    query.range('.location-item').rules({
        location: '.location-address',
        lat: '.map-container.js-open-detail@data-lat'
    }).concat()
    query.range('.business-detail ul').rules('li').concat()
    query.range('.swiper-container').rules('img@src').concat()
    query.rules('.job-sec-v2 .text.fold-text@html').concat()
         .rules('.company-culture .text.fold-text').concat()
         .rules('.company-develop .text.fold-text').concat()
         .rules('.company-talents .text.fold-text').concat()
         .rules('.company-talents-list li').concat()
    query.range('.company-products-new ul').rules({
        img: 'li img@src',
        desc: 'li .company-product-intro'
    }).concat()
    query.range('.manager-inner ul').rules({
        img: 'li .info-user img@src',
        name: 'li .name',
        job: 'li .job-title',
        desc: 'li .text fold-text'
    }).concat()
    query.rules('.work-time span').concat()
         .rules('.work-tags>.work-tag-item')
}


const formatData = (id: string, data: any) => {
    let json: any = {
        jId: id,
        locations: transformLocations(data[0]),
        pics: data[2],
        desc: _.isString(data[3]) ? data[3].split('<br>') : undefined,
        culture: data[4],
        develop: data[5],
        talents: data[6],
        talentsList: data[7],
        project: data[8],
        manager: data[9],
        workTime: data[10],
        workItems: data[11]
    }

    if (Array.isArray(data[1])) {
        data[1].forEach((k, i) => {
            const value = k.split('：')[1]
            json[keys1[i]] = value
        })
    }

    return json
}

const transformLocations = (locations: any) => {
    if (!_.isArray(locations)) {
        return undefined
    }
    return locations.map((k: any) => {
        let item: any = { location: k?.location }
        const parts = k?.lat?.split(',')
        if (parts) {
            item.longitude = parts[0]
            item.latitude = parts[1]
        }
        return item
    })
}

const setup = async () => {
    const jobs = await fetchJobs()
    const details = jobs.map((job: any) => {
        const html = readHtml(job.id, 'companys')
        const data = parseHtml(html)
        return formatData(job.id, data)
    })

    const json = JSON.stringify(details, null, 2)
    writeJson('companys', json)
    console.log(' => OK')
}

export default setup
